package com.bluno.conn;

import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;


@TargetApi(5)
public class Connecter extends Thread{
	private ConnManager manager;
	private BluetoothSocket socket;
	private List<BluetoothDevice> devices;
	private BluetoothDevice device;
	private int deviceIndex;
	public Connecter(ConnManager manager, List<BluetoothDevice> devices){
		deviceIndex = 0;
		this.manager = manager;
		this.devices = devices;
		
		device = devices.get(deviceIndex);
		
	

	}
	
	public void run() {
		// Always cancel discovery because it will slow down a connection
		//manager.getBtAdapter().cancelDiscovery();
		while(deviceIndex < devices.size())
		{
			BluetoothSocket tmp = null;
			try {
				tmp = device.createRfcommSocketToServiceRecord(ConnManager.MY_UUID);
			}catch(IOException e) {
			}
			this.socket = tmp;
			
			try {
				socket.connect();
			}catch(IOException e) {
				//connectionFailed();
				try {
					socket.close();
				} catch(IOException e2) {
					//log unable to close socket
				}
				System.out.println("NUM TEM");
				//manager.getConnecter().start();
				manager.launchConnectionFail(socket.getRemoteDevice().getName());
				return;
			}

			//Pega o socket aqui!!!
			manager.createConnection(socket,device.getAddress());
			++deviceIndex;
		}
		
		//synchronized (manager.getConnecter()) {
		//	manager.setConnecter(null);
		//}

	}
	
	public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            //failed to close socket
        }
    }
}
